package com.gxc.controller;

import com.gxc.service.PushService;
import java.util.Random;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * SSE（server send event）服务端发送事件.
 *
 * @author 宫新程
 * @since 2018/12/18 1:44 PM
 */
@Controller
@Slf4j
public class SseController {

  @Resource private PushService pushService;

  /** 测试. */
  @RequestMapping(value = "/push", produces = "text/event-stream")
  @ResponseBody
  public String push() {
    Random random = new Random();
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e.toString());
    }
    return "data:Testing 1,2,3" + random.nextInt() + "\n\n";
  }

  @RequestMapping("/defer")
  @ResponseBody
  public DeferredResult<String> deferredCall() {
    return pushService.getAsyncUpdate();
  }
}
